import { defaultRecentlyDay } from '@/utils/time';
import { excelDataAndMergeConf, handleModeType, markSlitData, MessageError, MessageWaring } from '@/utils/tool';
import { Button, Input, Radio, TreeSelect } from 'antd';
import { DateRangePicker } from 'element-react';
import { FC, useEffect, useRef, useState } from 'react';
import MarkingField from './MarkingFieldDialog';
const { SHOW_PARENT, SHOW_CHILD } = TreeSelect;
import './index.less';
import { TableList, MarkingTableProps } from './MarkingTable';
import { markingBackT, MarkingPageQueryT, MarkingSelectT } from '@/typings/global';
import { useStores } from '@/stores';
import { getMarkingBack } from '@/api/mark-page';
import { Storage } from '@/utils/storage';
// import xlsx from 'node-xlsx';
import { saveAs } from 'file-saver';
import XLSX from 'xlsx';
// import XLSXStyle from 'xlsx-style';
import ExcelJS from 'exceljs';
import moment from 'moment';
import { DownloadOutlined } from '@ant-design/icons';
import { MARK_LAYER_COLUMNS, UNIT_TO_M } from '@/utils/constant';
// 上述三个方法，可以合并成一个方法

// 这个页面根据业务来自行设计吧
const newPage: FC = () => {
  const { markingStore, lotStore } = useStores();
  const fieldRef = useRef<any>(null);
  const [queryType, setQueryType] = useState<MarkingPageQueryT>(MarkingPageQueryT.time);
  const [layerIdVal, setLayerIdVal] = useState<string>('');
  const [time, setTime] = useState<Array<Date>>(defaultRecentlyDay(7));
  const [notGoodList, setNotGoodList] = useState<Array<string>>(Storage.get('notGoodSelect') ? Storage.get('notGoodSelect') : ['all']); //  不良
  const [tableData, setTableData] = useState<markingBackT[]>();
  const [exportLoading, setExportLoading] = useState<boolean>(false); // 导出按钮的loading
  const modelResult = handleModeType(markingStore.allNotGoodType);
  const modeTreeData = modelResult.modeTreeData;
  markingStore.allNotGoodFatherMap = modelResult.allNotGoodFatherMap;

  // 模型树
  const modeTreeProps = {
    treeData: [
      {
        title: '全选',
        value: 'all',
        key: 'all',
        children: modeTreeData
      }
    ], // 不良的全集
    value: notGoodList, // 缺陷选中
    onChange: typeList => {
      setNotGoodList(typeList);
    },
    treeCheckable: true,
    showCheckedStrategy: SHOW_PARENT,
    placeholder: '请选择不良内容',
    style: {
      width: '220px'
    },
    maxTagCount: 1,
    treeDefaultExpandedKeys: ['all']
  };

  useEffect(() => {
    // console.log('---marking分析--lotStore.card.flawAlias',lotStore.card.flawAlias);
    initHandle();
  }, []);

  // 1 初始化的处理
  const initHandle = () => {
    dataQuerey(); //初始化查询，避免初次显示页面为空
  };

  // 2 查询
  const dataQuerey = async (type?) => {
    const isPass = checkQueryParamsPass(queryType, time, layerIdVal, notGoodList);
    if (!isPass) {
      MessageWaring('查询的条件不能为空！！！');
      return;
    }
    Storage.set('notGoodSelect', notGoodList);
    const backParams = handleSelectParams(queryType, time, layerIdVal, notGoodList);
    const data = getQueryReqData(backParams, type);
    return data;
  };

  // 核对查询条件是否合法//TODO:
  const checkQueryParamsPass = (queryType: MarkingPageQueryT, time: Array<Date>, layerIdVal: string, notGoodList: Array<number | string>) => {
    let isPass = true;
    if (queryType == MarkingPageQueryT.time) {
      if (!time || !time.length) {
        isPass = false;
      }
    } else {
      if (!layerIdVal) {
        isPass = false;
      } else {
        if (!layerIdVal.trim()) {
          isPass = false;
        }
      }
    }

    if (!notGoodList || !notGoodList.length) {
      isPass = false;
    }
    return isPass;
  };

  // 处理查询参数
  const handleSelectParams = (queryType: MarkingPageQueryT, time: Array<Date>, layerIdVal: string, notGoodList: Array<string | string>) => {
    const params = {} as any;
    if (queryType == MarkingPageQueryT.time) {
      params.startTime = new Date(time[0]).getTime();
      params.endTime = new Date(time[1]).getTime();
    } else {
      params.layerId = layerIdVal.trim();
    }
    // 这里要处理选中的不良Model，只要子集
    if (notGoodList[0] !== 'all') {
      const childArr: Array<number> = [];
      notGoodList.forEach(key => {
        const valArr = markingStore.allNotGoodFatherMap.get(key);
        if (valArr) {
          childArr.push(...valArr);
        } else {
          childArr.push(key as unknown as number);
        }
      });
      params.markingTypeList = childArr;
    }
    return params;
  };

  //   获取查询的请求数据
  const getQueryReqData = async (queryParams: MarkingSelectT, type?) => {
    try {
      const params = { ...queryParams, pageSize: markingStore.table.pageSize, pageNum: markingStore.table.currentPage };
      if (type == 'export') {
        // 如果是导出的话，默认查询所有数据
        params.pageNum = 0;
        params.pageSize = 0;
      }
      const resBack = await getMarkingBack(params);
      if (resBack.code === 200) {
        const tableData = resBack.data?.list?.map(item => {
          const layerInfo = item;
          layerInfo.key = layerInfo.layerId;
          layerInfo.layerHeight = ((layerInfo?.layerHeight as number) / UNIT_TO_M)?.toFixed(2);
          layerInfo.layerWidth = (layerInfo?.layerWidth as number)?.toFixed(2);
          layerInfo.layerPolPositionExactRatio = ((layerInfo?.layerPolPositionExactRatio as number) * 100)?.toFixed(2) + '%';
          layerInfo.layerPolPatternExactRatio = ((layerInfo?.layerPolPatternExactRatio as number) * 100)?.toFixed(2) + '%';
          layerInfo.layerPolPiantiehouOkRatio = ((layerInfo?.layerPolPiantiehouOkRatio as number) * 100)?.toFixed(2) + '%';
          return layerInfo;
        });

        setTableData(tableData as markingBackT[]);
        markingStore.table.total = resBack.data.total;
        return resBack.data;
      }
    } catch (error) {
      console.log(error);
      MessageError((error as any)?.response?.data?.message);
    }
    return null;
  };

  // 6 字段设置--打开对话框
  const openFieldDialog = () => {
    fieldRef.current.setShowFiledDialog(true);
  };
  //  7 字段设置--确定提交
  const submitfieldSet = checkedfieldArr => {
    // 为了使得字段更新直接渲染
    const data = [...(tableData as markingBackT[])];
    setTableData(data);
    fieldRef.current.setShowFiledDialog(false); // 关闭
  };

  // 使用exceljs实现导出
  const exportExcel = async () => {
    setExportLoading(true);
    try {
      const data = await dataQuerey();
      if (!data.list || data.list.length == 0) {
        setExportLoading(false);
        return MessageError('数据为空，无法导出！');
      }
      if (!markingStore.markingFieldChecked) {
        setExportLoading(false);
        return MessageError('至少设置一个字段！');
      }
      // 创建工作簿
      const workbook = new ExcelJS.Workbook();
      workbook.creator = 'leaper';
      workbook.created = new Date(2023, 10, 25);

      data.list?.forEach(layer => {
        // 添加工作表
        const worksheet = workbook.addWorksheet(layer.layerId);
        const handleData = markSlitData(layer);
        const config = excelDataAndMergeConf(handleData, markingStore.markingFieldChecked);

        // 添加大卷涂层信息
        const layerTitle = [] as string[];
        const layerData = [] as Array<string | number>;
        MARK_LAYER_COLUMNS.forEach(item => {
          layerTitle.push(item.title);
          layerData.push(layer[item.key]);
        });
        config.data.unshift(layerTitle, layerData, []);

        worksheet.addRows(config.data);
        // 合并单元格
        config.mergeConf?.forEach(item => {
          worksheet.mergeCells(item?.s.r, item?.s.c, item?.e.r, item?.e.c);
        });

        // 设置合并单元格的样式,只对有合并单元格操作的格子进行垂直居中操作
        worksheet.eachRow(row => {
          row.eachCell(cell => {
            if (cell.master) {
              cell.alignment = { vertical: 'middle' };
            }
          });
        });
      });

      // 生成Excel文件
      workbook.xlsx.writeBuffer().then(data => {
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `涂层信息_${moment().format('YYYY-MM-DD HH:mm:ss')}.xlsx`;
        a.click();
        window.URL.revokeObjectURL(url);
      });
      setExportLoading(false);
    } catch (error) {
      console.log('导出接口出错_关闭加载按钮', error);
      setExportLoading(false);
    }
  };

  return (
    <div className="marking-page">
      <div className="operator-bar">
        <Radio.Group
          style={{ marginLeft: 20 }}
          onChange={(e: any) => {
            setQueryType(e.target.value);
            if (e.target.value === MarkingPageQueryT.time) {
              setLayerIdVal('');
            }
          }}
          value={queryType}
        >
          <Radio value={MarkingPageQueryT.time}>检测时间:</Radio>
          <DateRangePicker
            className="hourTime"
            style={{ marginRight: 20 }}
            value={time}
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期范围"
            isShowTime={true}
            onChange={date => {
              console.debug('重新选择查询时间，重新设置到组件显示 time:', date);
              setTime(date);
            }}
            isDisabled={queryType === MarkingPageQueryT.lot}
          />
          <Radio value={MarkingPageQueryT.lot} style={{ marginLeft: 20 }}>
            涂层批号：
          </Radio>
        </Radio.Group>
        <Input
          className="lot-input"
          disabled={queryType === MarkingPageQueryT.time}
          allowClear={true}
          value={layerIdVal}
          onChange={val => {
            setLayerIdVal(val.target.value);
          }}
        ></Input>
        <Button type="primary" onClick={dataQuerey} style={{ marginLeft: 30 }}>
          查询
        </Button>
        <div style={{ display: 'inlineBlock', marginLeft: 10 }}>不良筛选：</div>
        <TreeSelect {...modeTreeProps} />
        <Button type="primary" ghost onClick={openFieldDialog} style={{ marginLeft: 10 }}>
          字段设置
        </Button>
        <div className="export">
          <Button type="primary" loading={exportLoading} icon={<DownloadOutlined />} onClick={exportExcel}>
            导出excel
          </Button>
        </div>
      </div>
      <TableList list={tableData as unknown as markingBackT[]} changePage={dataQuerey}></TableList>
      <MarkingField onRef={fieldRef} onSubmit={submitfieldSet}></MarkingField>
    </div>
  );
};
export default newPage;
